/**
 * 工具文件
 */

// 运行时缓存
let safeAreaInfo = null

// 获取设备信息
const getSafeArea = async () => {
  if (safeAreaInfo != null) {
    return safeAreaInfo
  }
  try {
    // 缓存获取
    safeAreaInfo = wx.getStorageSync('safeAreaInfo')
    // 缓存不存在 微信 API 获取
    if (!safeAreaInfo) {
      safeAreaInfo = await getSafeAreaByWx()
      // 存储缓存
      wx.setStorage({
        key: 'safeAreaInfo',
        data: safeAreaInfo
      })
    }
    return safeAreaInfo
  } catch (error) {
    wx.showModal({
      title: '绘制界面异常',
      content: '为了提供更好的体验 请点击右上角三个点 并点击【重新进入小程序】',
      cancelColor: '#464646',
      confirmColor: '#ee0a24'
    })
  }
}

/**
 * 获取设备信息
 * version      当前基础库版本
 * isIPhoneX    是否iPhoneX适配
 * barHeight    状态栏高度
 * winHeight    可视窗口高度
 */
const getSafeAreaByWx = () => {
	return new Promise((resolve, reject) => {
		wx.getSystemInfo({
      success: ({ SDKVersion, model, screenHeight, windowHeight, statusBarHeight, windowWidth }) => {
        const iphoneX = /iphone x/i.test(model)
        const iphoneNew = /iPhone11/i.test(model) && screenHeight === 812
        const safeAreaInfo = {
          version: SDKVersion,
          isIPhoneX: iphoneX || iphoneNew,
          barHeight: statusBarHeight || 20,
          winHeight: windowHeight,
          winWidth: windowWidth
        };
        resolve(safeAreaInfo)
      },
      fail: reject
    })
	})
}

/**
 * 自定义时间格式化
 * @param any time 
 * @param string reg 
 */
const formatTime = (time, reg) => {
  if (!time) return '-'
  const date = typeof time === 'string' ? new Date(time.replace(/-/g, '/')) : new Date(time)
  const map = {}
  map.yyyy = date.getFullYear()
  map.yy = ('' + map.yyyy).substr(2)
  map.M = date.getMonth() + 1
  map.MM = formatNumber(map.M)
  map.d = date.getDate()
  map.dd = formatNumber(map.d)
  map.H = date.getHours()
  map.HH = formatNumber(map.H)
  map.m = date.getMinutes()
  map.mm = formatNumber(map.m)
  map.s = date.getSeconds()
  map.ss = formatNumber(map.s)
  return reg.replace(/\byyyy|yy|MM|M|dd|d|HH|H|mm|m|ss|s\b/g, $1 => map[$1])
}

/**
 * 个数补零
 * @param number num 
 */
const formatNumber = (num) => {
  num = num + ''
  return num[1] ? num : `0${num}`
}

/**
 * 替换标点符号
 * @param {*} str 原字符串
 * @param {*} replacement 替换的字符
 */
const replaceSymbol = (str, replaceStr = '') => {
  if (isStrEmpty(str)) return ''
  return str.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\，|\。|\>|\/|\?]/g, replaceStr);
}

/**
 * 睡眠
 * @param {*} delay 延迟毫秒 
 */
const sleep = (delay = 2000) => {
  return new Promise((resolve) => {
    setTimeout(resolve, delay)
  })
}

// 验证有效字符串
const isStrEmpty = str => {
  if (typeof str == 'undefined' || !str || !str.replace(/\s+/g, '')) {
    return true
  } else {
    return false
  }
}

/**
 * 金额小数点保留后两位
 * @param {*} price 
 */
const formatPrice = (price) => {
  price = parseFloat(price)
  if (isNaN(price)) return '0.00'
  price = price + ''
  
  const index = price.indexOf('.')
  if (index == -1) return price + '.00'

  let end = price.slice(index, index + 3)
	if (end.length == 2) end += '0'

	return parseInt(price) + end
}

module.exports = {
  getSafeArea,
  getSafeAreaByWx,
  formatTime,
  formatNumber,
  replaceSymbol,
  sleep,
  isStrEmpty,
  formatPrice
}
